package com.heima;

import org.apache.catalina.LifecycleException;
import org.apache.catalina.Server;
import org.apache.catalina.Service;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardEngine;
import org.apache.catalina.core.StandardHost;
import org.apache.catalina.startup.Tomcat;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class TomcatWebServer implements WebServer {
    private Tomcat tomcat;
    private WebApplicationContext applicationContext;
    
    public TomcatWebServer(WebApplicationContext applicationContext) {
        this.tomcat = new Tomcat();
        this.applicationContext = applicationContext;
    }
    
    public void start() {
        System.out.println("TomcatWebServer is starting...");
        
        // 配置Tomcat
        Server server = tomcat.getServer();
        Service service = server.findService("Tomcat");
        
        Connector connector = new Connector();
        connector.setPort(8080);
        
        StandardEngine engine = new StandardEngine();
        engine.setDefaultHost("localhost");
        
        StandardHost host = new StandardHost();
        host.setName("localhost");
        
        String contextPath = "";
        StandardContext context = new StandardContext();
        context.setPath(contextPath);
        context.addLifecycleListener(new Tomcat.FixContextListener());
        
        // 添加DispatcherServlet处理Spring MVC请求
        Tomcat.addServlet(context, "dispatcher", new DispatcherServlet(this.applicationContext));
        context.addServletMappingDecoded("/*", "dispatcher");
        
        host.addChild(context);
        engine.addChild(host);
        
        service.setContainer(engine);
        service.addConnector(connector);
        
        try {
            tomcat.start();
            server.await(); // 保持服务器运行状态
        } catch (LifecycleException e) {
            e.printStackTrace();
        }
    }
}